package daily.may0531;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SafeSellTicketByLockTest {
    public static void main(String[] args) {
        //匿名内部类
        Runnable tw = new Runnable() {
            //定义一个多个线程共享的票源
            private int tickets = 100;
            //在成员位置通过Lock接口实现类ReentrantLock创建一个Lock锁对象
            Lock lock = new ReentrantLock();

            //设置线程任务:卖票
            @Override
            public void run() {
                //使用死循环,让卖票操作重复执行
                while (true) {
                    //在可能会出现安全问题的代码前调用lock方法获取锁
                    lock.lock();
                    if (tickets > 0) {
                        //使用finally代码块保证锁的释放
                        try {
                            Thread.sleep(10);
                            System.out.printf("%s窗口第%d张票已经售出\n", Thread.currentThread().getName(), tickets--);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } finally {
                            //在可能会出现安全问题的代码后调用unlock方法释放锁
                            lock.unlock();
                        }
                    }
                }
            }
        };
        //4个窗口一起卖票
        new Thread(tw, "窗口1").start();
        new Thread(tw, "窗口2").start();
        new Thread(tw, "窗口3").start();
        new Thread(tw, "窗口4").start();
    }
}
